import React from 'react'
import {Form,Input,Button,Switch, Toast} from 'antd-mobile'
import request from '../../api/request'
import {useDispatch} from 'react-redux'
import { updateData } from '../../store/modules/user'
import {useNavigate} from 'react-router-dom'
import { usedebounce } from '../../hooks/useDebounce'
function Index() {
  const dispatch=useDispatch()
  const navigate=useNavigate()
  const [goLogin]=Form.useForm()
 const onFinish=(values)=>{
  if(!values.state===true){
      Toast.show({
          content:'状态未选中',
          icon:'fail'
        })
        return
  }
   request.post('/login',values).then(res=>{
    console.log('登录',res)
    const {code,data,message}=res.data 
    if(code===10000)
    {
       //存储到仓库
        dispatch(updateData(data))
        Toast.show({ 
          content:message,
          icon:'success'
        })
        navigate('/my')
    }else{
       Toast.show({
          content:message,
          icon:'fail'
        })
    }
   })
 }
 const login=usedebounce(()=>{
    goLogin.submit()
 })
 
  return (
    <div>
     <Form
     onFinish={onFinish}
       form={goLogin}
        layout='horizontal'
        footer={
          <Button block  color='primary' size='large' onClick={login}>
            登录
          </Button>
        }
      >
        <Form.Header>
           <h1 style={{textAlign:'center'}}>登录系统</h1>
        </Form.Header>
        <Form.Item
          name='username'
          label='手机号'
          rules={[{ required: true, message: '手机号不能为空' },{pattern:/^13\d{9}$/,message:'手机号不符合要求'}]}
        >
          <Input  placeholder='请输入手机号' />
        </Form.Item>
        <Form.Item name='password' label='密码'  rules={[{ required: true, message: '密码不能为空' },{pattern:/\w{6,20}/,message:'密码不少于6位'}]}>
         <Input  placeholder='请输入密码' />
        </Form.Item>
        
        <Form.Item
          name='state'
          label='同意协议'
          valuePropName="checked"
          childElementPosition='right'
        >
          <Switch />
        </Form.Item>
      </Form>
    </div>
  )
}

export default Index
